package com.atguigu.tingshu.search.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.ElasticsearchException;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.aggregations.Buckets;
import co.elastic.clients.elasticsearch._types.aggregations.LongTermsBucket;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.CompletionSuggestOption;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.JsonData;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.AlbumFeignClient;


import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.thread.ThreadPoolConfig;
import com.atguigu.tingshu.model.album.*;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.atguigu.tingshu.query.album.AlbumInfoQuery;
import com.atguigu.tingshu.query.search.AlbumIndexQuery;
import com.atguigu.tingshu.search.receiver.SearchReceiver;
import com.atguigu.tingshu.search.repository.AlbumInfoRepository;
import com.atguigu.tingshu.search.repository.SuggestIndexRepository;
import com.atguigu.tingshu.search.service.SearchService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.album.AlbumStatVo;
import com.atguigu.tingshu.vo.search.AlbumInfoIndexVo;
import com.atguigu.tingshu.vo.search.AlbumSearchResponseVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.micrometer.common.util.StringUtils;
import co.elastic.clients.elasticsearch.core.search.Suggestion;
import io.netty.util.internal.StringUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import org.springframework.data.elasticsearch.core.suggest.Completion;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Slf4j
@Service
@SuppressWarnings({"all"})
public class SearchServiceImpl implements SearchService {
    private static final String INDEX_NAME = "albuminfo";
    private static final String SUGGESTINFO_INDEX_NAME = "suggestinfo";
    @Autowired
    private AlbumFeignClient albumFeignClient;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private AlbumInfoRepository albumInfoRepository;
    @Autowired
    private SuggestIndexRepository suggestIndexRepository;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    private ElasticsearchClient elasticsearchClient;

    @Autowired
    private RedisTemplate redisTemplate;




    /**
     * 获取排行榜
     * /api/search/albumInfo/findRankingList/{category1Id}/{dimension}
     */
    @Override
    public List<AlbumInfoIndex> findRankingList(Long category1Id, String dimension) {
        //定义一个key,对应存入的key
        String key = RedisConstant.RANKING_KEY_PREFIX + category1Id;
        Boolean aBoolean = redisTemplate.opsForHash().hasKey(key, dimension);
        if (aBoolean){
            List<AlbumInfoIndex> list = (List<AlbumInfoIndex>) redisTemplate.opsForHash().get(key, dimension);
            return list;
        }
        return null;
    }


    /**
     * 更新所有分类下排行榜-手动调用
     * /api/search/albumInfo/updateLatelyAlbumRanking
     */
    @Override
    @SneakyThrows
    public void updateLatelyAlbumRanking() {
        //查询所有一级分类id
        List<BaseCategory1> baseCategory1List = albumFeignClient.findAllCategory1().getData();
        Assert.notNull(baseCategory1List,"查询所有一级分类为空,异常");
        //处理集合为只有id的
        List<Long> collect = baseCategory1List.stream().map(BaseCategory1::getId).collect(Collectors.toList());
        ///循环
        for (Long aLong : collect) {
            //创建一个集合存放五种排行方式
            String[] rankingDimensionArray = new String[]{"hotScore", "playStatNum", "subscribeStatNum", "buyStatNum", "commentStatNum"};
            for (String rankingDimension : rankingDimensionArray) {
                SearchResponse<AlbumInfoIndex> category1Id1 = elasticsearchClient.search(s -> s
                                .index(INDEX_NAME)
                                .query(q -> q.term(t -> t.field("category1Id").value(aLong)))
                                .sort(so -> so.field(fi -> fi.field(rankingDimension).order(SortOrder.Desc)))
                                .size(20)
                        , AlbumInfoIndex.class);
                //解析es
                List<Hit<AlbumInfoIndex>> hits = category1Id1.hits().hits();
                List<AlbumInfoIndex> albumInfoIndexList = hits.stream().map(hit -> hit.source()).collect(Collectors.toList());

                //定义一个key
                String key = RedisConstant.RANKING_KEY_PREFIX + aLong;
                redisTemplate.opsForHash().put(key,rankingDimension,albumInfoIndexList);
            }
        }
    }




    /**
     * 查询专辑 详情
     * /api/search/albumInfo/{albumId}
     */
    @Override
    public Map<String, Object> getItem(Long albumId) {
        Map<String, Object> map = new ConcurrentHashMap<>();
        //获取专辑信息
        CompletableFuture<AlbumInfo> albumInfoPool = CompletableFuture.supplyAsync(() -> {
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
            Assert.notNull(albumInfo, "查询专辑ID：{},出现异常", albumId);
            //封装结果
            map.put("albumInfo", albumInfo);
            return albumInfo;
        }, threadPoolExecutor);
        //获取一,二,三级的ID和NAME
        CompletableFuture<Void> baseCategoryView1 = albumInfoPool.thenAcceptAsync(albumInfo -> {
            BaseCategoryView baseCategoryView = albumFeignClient.getCategoryView(albumInfo.getCategory3Id()).getData();
            Assert.notNull(baseCategoryView, "查询三级分类ID：{},出现异常", albumInfo.getCategory3Id());
            //封装结果
            map.put("baseCategoryView", baseCategoryView);
        }, threadPoolExecutor);
        //获取主播信息
        CompletableFuture<Void> announcer = albumInfoPool.thenAcceptAsync(albumInfo -> {
            UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(albumInfo.getUserId()).getData();
            Assert.notNull(userInfoVo, "获取主播信息，用户ID:{},出现异常", albumInfo.getUserId());
            map.put("announcer", userInfoVo);
        }, threadPoolExecutor);
        //获取专辑统计信息
        CompletableFuture<Void> albumStatVo1 = CompletableFuture.runAsync(() -> {
            AlbumStatVo albumStatVo = albumFeignClient.getAlbumStatVo(albumId).getData();
            Assert.notNull(albumStatVo, "获取专辑统计信息,专辑ID:{},出现异常", albumId);
            map.put("albumStatVo", albumStatVo);
        }, threadPoolExecutor);
        CompletableFuture.allOf(
                albumInfoPool,
                baseCategoryView1,
                announcer,
                albumStatVo1
        ).join();

        return map;
    }




    /**
     * 专辑检索
     * /api/search/albumInfo
     */
    @Override
    @SneakyThrows
    public AlbumSearchResponseVo albumInfo(AlbumIndexQuery albumIndexQuery) {
        //构建请求对象
        SearchRequest searchRequest = this.buildDsl(albumIndexQuery);
        String s = searchRequest.toString();
        System.out.println("-------------------------------------"+s);

        //执行查询
        SearchResponse<AlbumInfoIndex> search = elasticsearchClient.search(searchRequest, AlbumInfoIndex.class);

        //转换
        AlbumSearchResponseVo albumSearchResponseVo = this.conversionResult(search,albumIndexQuery);


        return albumSearchResponseVo;
    }

    /**
     * 查询指定一级分类下热门排行专辑
     * /api/search/albumInfo/channel/{category1Id}
     */
    @Override
    public List<Map<String, Object>> channel(Long category1Id) {
        //封装对象
        List<Map<String, Object>> list = null;
        try {
            //根据一级分类id获取七个三级分类
            List<BaseCategory3> baseCategory3List = albumFeignClient.findTopBaseCategory3(category1Id).getData();
            //将list转为map
            Map<Long, BaseCategory3> baseCategory3Map = baseCategory3List.stream().collect(Collectors.toMap(BaseCategory3::getId, baseCategory3 -> baseCategory3));

            //验证是否为null
            Assert.notNull(baseCategory3List, "一级分类{}未包含置顶三级分类", category1Id);
            //筛选出只有三级分类id的集合
            List<Long> collect = baseCategory3List.stream().map(BaseCategory3::getId).collect(Collectors.toList());
            //构建条件
            List<FieldValue> collect1 = collect.stream().map(category3Id -> {
                FieldValue fieldValue = FieldValue.of(category3Id);
                return fieldValue;
            }).collect(Collectors.toList());
            //发送请求查询es
            SearchResponse<AlbumInfoIndex> search = elasticsearchClient.search(s -> s.index(INDEX_NAME)
                            .query(q -> q.terms(t -> t.field("category3Id").terms(te -> te.value(collect1))))
                            .aggregations("category3Agg", a -> a
                                    .terms(te -> te.field("category3Id").size(10))
                                    .aggregations("top6Agg", ag -> ag.topHits(to -> to.sort(sor -> sor.field(fi -> fi.field("hotScore").order(SortOrder.Desc))).size(6)))
                            )
                            .size(0)
                    , AlbumInfoIndex.class);
            //解析查询结果
            Aggregate category3Agg = search.aggregations().get("category3Agg");
            Buckets<LongTermsBucket> buckets = category3Agg.lterms().buckets();
            List<LongTermsBucket> array = buckets.array();
            if (CollectionUtil.isNotEmpty(array)){
                list = array.stream().map(bucket -> {
                    Map<String,Object> map = new HashMap<>();
                    long key = bucket.key();
                    BaseCategory3 baseCategory3 = baseCategory3Map.get(key);
                    map.put("baseCategory3",baseCategory3);
                    //获取数据集合
                    Aggregate top6Agg = bucket.aggregations().get("top6Agg");
                    List<Hit<JsonData>> hits = top6Agg.topHits().hits().hits();
                    if (CollectionUtil.isNotEmpty(hits)){
                        List<AlbumInfoIndex> collect2 = hits.stream().map(jsonDataHit -> {
                            //获取数据结果
                            JsonData source = jsonDataHit.source();
                            //转换数据
                            AlbumInfoIndex albumInfoIndex = JSON.parseObject(source.toString(), AlbumInfoIndex.class);
                            return albumInfoIndex;

                        }).collect(Collectors.toList());
                        map.put("list",collect2);
                    }
                    return map;
                }).collect(Collectors.toList());
            }

        }  catch (IOException e) {
            log.error("[检索服务]首页热门专辑异常：{}", e);
            throw new RuntimeException(e);
        }
        return list;
    }

    private AlbumSearchResponseVo conversionResult(SearchResponse<AlbumInfoIndex> search, AlbumIndexQuery albumIndexQuery) {
        AlbumSearchResponseVo albumSearchResponseVo = new AlbumSearchResponseVo();
        //设置每页条数
        albumSearchResponseVo.setPageSize(albumIndexQuery.getPageSize());
        //设置当前页
        albumSearchResponseVo.setPageNo(albumSearchResponseVo.getPageNo());
        //设置总页数
        long value = search.hits().total().value();
        albumSearchResponseVo.setTotal(value);
        //设置总页数
        albumSearchResponseVo.setTotalPages(value%albumSearchResponseVo.getPageSize()==0?value/albumSearchResponseVo.getPageSize():value/albumSearchResponseVo.getPageSize()+1);
        //获取查询结果的数据
        List<Hit<AlbumInfoIndex>> hits = search.hits().hits();
        if (CollectionUtil.isNotEmpty(hits)){
            List<AlbumInfoIndexVo> collect = hits.stream().map(hit -> {
                //结果数据
                AlbumInfoIndexVo albumInfoIndexVo = BeanUtil.copyProperties(hit.source(), AlbumInfoIndexVo.class);

                //获取高亮
                Map<String, List<String>> highlight = hit.highlight();
                //判断
                if (highlight!=null && highlight.containsKey("albumTitle")){

                    String albumTitle = highlight.get("albumTitle").get(0);
                    //覆盖不带高亮的
                    albumInfoIndexVo.setAlbumTitle(albumTitle);
                }


                return albumInfoIndexVo;
            }).collect(Collectors.toList());
            //封装
            albumSearchResponseVo.setList(collect);

        }
        return albumSearchResponseVo;
    }


    /**
     * 转换结果
     * @param search
     * @return
     */



    /**
     * DSL语句，返回请求对象
     * @param albumInfoQuery
     * @return
     */
    private SearchRequest buildDsl(AlbumIndexQuery albumIndexQuery) {
        //创建请求对象
        SearchRequest.Builder builder = new SearchRequest.Builder();
        //用builder添加条件
        builder.index(INDEX_NAME);
        //创建多条件查询
        BoolQuery.Builder allBool = new BoolQuery.Builder();
        //关键字封装query---------------------------------------------------------------
        String keyword = albumIndexQuery.getKeyword();
        if (StringUtils.isNotEmpty(keyword)){
            //创建一个bool
            BoolQuery.Builder bool = new BoolQuery.Builder();
            //设置标题
            bool.should(s->s.match(m->m.field("albumTitle").query(keyword)));
            //设置简介
            bool.should(s->s.match(m->m.field("albumIntro").query(keyword)));
            //设置主播昵称
            bool.should(s->s.term(t->t.field("announcerName").value(keyword)));

            //添加条件到外层我bool
            allBool.must(bool.build()._toQuery());
        }
        //封装三级分类---------------------------------------------------------------
        if (albumIndexQuery.getCategory1Id()!=null){
            allBool.filter(f->f.term(t->t.field("category1Id").value(albumIndexQuery.getCategory1Id())));
        }
        if (albumIndexQuery.getCategory2Id()!=null){
            allBool.filter(f->f.term(t->t.field("category2Id").value(albumIndexQuery.getCategory2Id())));
        }
        if (albumIndexQuery.getCategory3Id()!=null){
            allBool.filter(f->f.term(t->t.field("category3Id").value(albumIndexQuery.getCategory3Id())));
        }
        //专辑属性设置---------------------------------------------------------------
        List<String> attributeList = albumIndexQuery.getAttributeList();
        if (CollectionUtil.isNotEmpty(attributeList)){
            for (String attribute : attributeList) {
                String[] split = attribute.split(":");
                //判断数组
                if (split!=null && split.length==2){
                    //获取attributeId
                    String attributeId = split[0];
                    //获取valueId
                    String valueId = split[1];

                    allBool.filter(f->f.nested(n->n.path("attributeValueIndexList")
                            .query(q->q.bool(b->b
                                    .filter(fi->fi.term(t->t.field("attributeValueIndexList.attributeId").value(attributeId)))
                                    .filter(fil->fil.term(tt->tt.field("attributeValueIndexList.valueId").value(valueId)))
                    ))));
                }
            }
        }
        //设置条件查询
        builder.query(allBool.build()._toQuery());
        //设置分页
        builder.from((albumIndexQuery.getPageNo() - 1) * albumIndexQuery.getPageSize());
        builder.size(albumIndexQuery.getPageSize());
        //设置高亮
        if (StringUtils.isNotEmpty(keyword)){
            builder.highlight(h->h.fields("albumTitle"
                    ,hf->hf.preTags("<font color='red'>")
                    .postTags("</font>")));
        }
        //设置排序  排序（综合排序[1:desc] 播放量[2:desc] 发布时间[3:desc]；asc:升序 desc:降序）
        String order = albumIndexQuery.getOrder();
        if (StringUtils.isNotEmpty(order)){
            String[] split = order.split(":");
            if (split!=null && split.length==2){
                //获取根据什么排序
                String s0 = split[0];
                //获取排序方式
                String s1 = split[1];

                String fs ="";
                switch (s0){
                    case "1":
                        fs="hotScore";
                        break;
                    case "2":
                        fs="playStatNum";
                        break;
                    case "3":
                        fs="createTime";
                        break;
                }
                String fss = fs;

                builder.sort(s->s.field(f->f.field(fss).order("asc".equals(s1)? SortOrder.Asc:SortOrder.Desc)));
            }
            //过滤结果
            builder.source(s->s.filter(f->f.excludes("category1Id", "category2Id", "category3Id")));


        }


        SearchRequest build = builder.build();
        return build;
    }

    /**
     * 上架专辑-导入索引库
     * 优化后
     * /api/search/albumInfo/upperAlbum/{albumId}
     */
    @Override
    public void upperAlbum(Long albumId) {
        //封装
        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();

        CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            //根据id查询专辑信息
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
            //Assert.isNull(albumInfo,"专辑不存在",albumId);
            BeanUtil.copyProperties(albumInfo, albumInfoIndex);
            //获取属性值集合
            List<AlbumAttributeValue> albumAttributeValueVoList = albumInfo.getAlbumAttributeValueVoList();
            //判断
            if (CollectionUtil.isNotEmpty(albumAttributeValueVoList)) {
                List<AttributeValueIndex> collect = albumAttributeValueVoList.stream().map(albumAttributeValue -> {
                    return BeanUtil.copyProperties(albumAttributeValue, AttributeValueIndex.class);
                }).collect(Collectors.toList());

                albumInfoIndex.setAttributeValueIndexList(collect);
            }

            return albumInfo;
        },threadPoolExecutor);

        CompletableFuture<Void> userInfoCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            //获取作者的信息
            UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(albumInfo.getUserId()).getData();
            //判断
            Assert.notNull(userInfoVo, "用户查询异常，用户ID{}", albumInfo.getUserId());
            albumInfoIndex.setAnnouncerName(userInfoVo.getNickname());
        },threadPoolExecutor);

        CompletableFuture<Void> OneCompletableFuture1 = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            //获取一级二级三级的分类ID
            BaseCategoryView baseCategoryView = albumFeignClient.getCategoryView(albumInfo.getCategory3Id()).getData();
            //判断
            Assert.notNull(baseCategoryView, "分页查询异常，分类的ID{}", albumInfo.getCategory3Id());
            albumInfoIndex.setCategory1Id(baseCategoryView.getCategory1Id());
            albumInfoIndex.setCategory2Id(baseCategoryView.getCategory2Id());
        },threadPoolExecutor);

        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            //存入专辑统计
            int num1 = RandomUtil.randomInt(1000, 2000);
            int num2 = RandomUtil.randomInt(500, 1000);
            int num3 = RandomUtil.randomInt(200, 400);
            int num4 = RandomUtil.randomInt(100, 200);
            albumInfoIndex.setPlayStatNum(num1);
            albumInfoIndex.setSubscribeStatNum(num2);
            albumInfoIndex.setBuyStatNum(num3);
            albumInfoIndex.setCommentStatNum(num4);

            //5.2 基于统计值计算出专辑得分 为不同统计类型设置不同权重
            BigDecimal bigDecimal1 = new BigDecimal(num4).multiply(new BigDecimal("0.4"));
            BigDecimal bigDecimal2 = new BigDecimal(num3).multiply(new BigDecimal("0.3"));
            BigDecimal bigDecimal3 = new BigDecimal(num2).multiply(new BigDecimal("0.2"));
            BigDecimal bigDecimal4 = new BigDecimal(num1).multiply(new BigDecimal("0.1"));
            BigDecimal hotScore = bigDecimal1.add(bigDecimal2).add(bigDecimal3).add(bigDecimal4);
            albumInfoIndex.setHotScore(hotScore.doubleValue());
        },threadPoolExecutor);

        CompletableFuture.allOf(albumInfoCompletableFuture,
                userInfoCompletableFuture,
                OneCompletableFuture1,
                voidCompletableFuture
                ).join();

        albumInfoRepository.save(albumInfoIndex);

        //建立题词库
        this.saveSuggestIndex(albumInfoIndex);
    }

    /**
     * 构建题词库
     * @param albumInfoIndex
     */
    @Override
    public void saveSuggestIndex(AlbumInfoIndex albumInfoIndex) {
        //创建提词对象
        SuggestIndex suggestIndex = new SuggestIndex();
        //设置提词对象id
        suggestIndex.setId(albumInfoIndex.getId().toString());
        //设置提词对象title
        suggestIndex.setTitle(albumInfoIndex.getAlbumTitle());
        //设置提词对象 汉字提词或者单词
        suggestIndex.setKeyword(new Completion(new String[]{albumInfoIndex.getAlbumTitle()}));
        //设置提词对象 拼音提词
        suggestIndex.setKeywordPinyin(new Completion(new String[]{PinyinUtil.getPinyin(albumInfoIndex.getAlbumTitle(), "")}));
        //设置提词对象 首字母缩写提词
        suggestIndex.setKeywordSequence(new Completion(new String[]{PinyinUtil.getFirstLetter(albumInfoIndex.getAlbumTitle(), "")}));

        //添加到提词库
        suggestIndexRepository.save(suggestIndex);

                //TODO 这里重看
    }

    /**
     * 关键字自动补全
     * /api/search/albumInfo/completeSuggest/{keyword}
     */
    @Override
    public List<String> completeSuggest(String keyword) {
        try {
            //1.查询题词库

            //构建查询题词库DSL,获取查询结果
            SearchResponse<SuggestIndex> searchResponse = elasticsearchClient.search(s ->s.index(SUGGESTINFO_INDEX_NAME)
                            .suggest(su -> su
                                    .suggesters("mySuggestKeyword", fi -> fi.prefix(keyword).completion(c -> c.field("keyword").size(10).skipDuplicates(true)))
                                    .suggesters("mySuggestPinyin", fi -> fi.prefix(keyword).completion(c -> c.field("keywordPinyin").size(10).skipDuplicates(true)))
                                    .suggesters("mySuggestSequence", fi -> fi.prefix(keyword).completion(c -> c.field("keywordSequence").size(10).skipDuplicates(true))))
                    , SuggestIndex.class);

            //封装结果--去重 set集合
            Set<String> titleSet = new LinkedHashSet<>();
            titleSet.addAll(this.parseSuggestResult("mySuggestKeyword", searchResponse));
            titleSet.addAll(this.parseSuggestResult("mySuggestPinyin", searchResponse));
            titleSet.addAll(this.parseSuggestResult("mySuggestPinyin", searchResponse));

            System.out.println(titleSet);

            //结果不足10条
            if(titleSet.size()>=10){
                return new ArrayList<>(titleSet).subList(0,10);
            }

            //2.查询专辑索引库
            SearchResponse<AlbumInfoIndex> albumInfoIndexSearchResponse = elasticsearchClient.search(s -> s.index(INDEX_NAME).query(q -> q.match(m -> m.field("albumTitle").query(keyword))), AlbumInfoIndex.class);


            //解析结果
            List<Hit<AlbumInfoIndex>> hitList = albumInfoIndexSearchResponse.hits().hits();
            //判断
            if(CollectionUtil.isNotEmpty(hitList)){

                //遍历处理
                for (Hit<AlbumInfoIndex> albumInfoIndexHit : hitList) {
                    AlbumInfoIndex albumInfoIndex = albumInfoIndexHit.source();
                    titleSet.add(albumInfoIndex.getAlbumTitle());

                    //判断
                    if(titleSet.size()>=10){

                        break;

                    }
                }
            }

            //存储到结果集合中

            return new ArrayList<>(titleSet);
        } catch (IOException e) {
            log.error("[搜索服务]建议词自动补全异常：{}", e);
            throw new RuntimeException(e);
        }
    }



    /**
     * 解析题词查询结果
     *
     * @param mySuggestKeyword
     * @param searchResponse
     * @return
     */
    private Collection<String> parseSuggestResult(String suggestKeyword, SearchResponse<SuggestIndex> searchResponse) {


        //获取题词组数据
        List<Suggestion<SuggestIndex>> suggestions = searchResponse.suggest().get(suggestKeyword);

        //创建接收结果的集合
        List<String> list=new ArrayList<>();

        //遍历
        for (Suggestion<SuggestIndex> suggestion : suggestions) {
            //根据suggestions获取补全信息
            List<CompletionSuggestOption<SuggestIndex>> options = suggestion.completion().options();
            //判断
            if(CollectionUtil.isNotEmpty(options)){
                for (CompletionSuggestOption<SuggestIndex> option : options) {
                    SuggestIndex suggestIndex = option.source();
                    list.add(suggestIndex.getTitle());
                }
            }
        }
        return list;
    }



    @Override
    public void lowerAlbum(Long albumId) {
        albumInfoRepository.deleteById(albumId);
    }



    /**
     * 上架专辑-导入索引库
     * 优化前
     * /api/search/albumInfo/upperAlbum/{albumId}
     */
//    @Override
//    public void upperAlbum(Long albumId) {
//        //封装
//        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();
//        //根据id查询专辑信息
//        AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
//        BeanUtil.copyProperties(albumInfo,albumInfoIndex);
//        //获取属性值集合
//        List<AlbumAttributeValue> albumAttributeValueVoList = albumInfo.getAlbumAttributeValueVoList();
//        //判断
//        if (CollectionUtil.isNotEmpty(albumAttributeValueVoList)){
//            List<AttributeValueIndex> collect = albumAttributeValueVoList.stream().map(albumAttributeValue -> {
//                return BeanUtil.copyProperties(albumAttributeValue, AttributeValueIndex.class);
//            }).collect(Collectors.toList());
//
//            albumInfoIndex.setAttributeValueIndexList(collect);
//        }
//
//
//        //获取作者的信息
//        UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(albumInfo.getUserId()).getData();
//        albumInfoIndex.setAnnouncerName(userInfoVo.getNickname());
//
//        //获取一级二级三级的分类ID
//        BaseCategoryView baseCategoryView = albumFeignClient.getCategoryView(albumInfo.getCategory3Id()).getData();
//        BeanUtil.copyProperties(baseCategoryView,albumInfoIndex);
//
//
//        //存入专辑统计
//        int num1 = RandomUtil.randomInt(1000, 2000);
//        int num2 = RandomUtil.randomInt(500, 1000);
//        int num3 = RandomUtil.randomInt(200, 400);
//        int num4 = RandomUtil.randomInt(100, 200);
//        albumInfoIndex.setPlayStatNum(num1);
//        albumInfoIndex.setSubscribeStatNum(num2);
//        albumInfoIndex.setBuyStatNum(num3);
//        albumInfoIndex.setCommentStatNum(num4);
//
//
//        //5.2 基于统计值计算出专辑得分 为不同统计类型设置不同权重
//        BigDecimal bigDecimal1 = new BigDecimal(num4).multiply(new BigDecimal("0.4"));
//        BigDecimal bigDecimal2 = new BigDecimal(num3).multiply(new BigDecimal("0.3"));
//        BigDecimal bigDecimal3 = new BigDecimal(num2).multiply(new BigDecimal("0.2"));
//        BigDecimal bigDecimal4 = new BigDecimal(num1).multiply(new BigDecimal("0.1"));
//        BigDecimal hotScore = bigDecimal1.add(bigDecimal2).add(bigDecimal3).add(bigDecimal4);
//        albumInfoIndex.setHotScore(hotScore.doubleValue());
//
//        albumInfoRepository.save(albumInfoIndex);
//    }

}
